<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_exce'" type="danger" size="small" @click="onclick">excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增角色</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="username">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100px;higth:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增角色"

        :visible.sync="showDialog"
        @close="hClose"
      >
        <empDialog ref="mepDialog" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="AssignRoleDialog"
      >
        <AssignRole
          v-if="AssignRoleDialog"
          :role-id="roleId"
          @close="AssignRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import empDialog from '@/views/employees/empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees.js'
import AssignRole from './assignRole.vue'
console.log(employeesEnum.hireType, 'employeesEnum')
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '', // 保存ID
      AssignRoleDialog: false,
      showDialog: false, // 控制新增弹层关闭隐藏
      list: [], // 获取员工列表
      page: 1, // 页码值
      size: 5, // 每页显示的条数
      total: 0 // 保存员工的总数
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 分配角色
    hAssign(id) {
      this.roleId = id
      this.AssignRoleDialog = true
    },
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadEmployeeList()
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
      // console.log(`当前页: ${val}`)
    },
    // 要求返回的是正式与非正式
    hireTypeFormat(data) {
      return hireType[data] || '未知'
    },
    // 加载员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log(res, '123456')
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 子传父 重新渲染数据 关闭弹层
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployeeList()
      this.showDialog = false
    },
    // 充值表单
    hClose() {
      this.$refs.mepDialog.resetForm()
    },
    // 实现删除
    hDel(id) {
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        console.log(res, '11111')
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    dataForm(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 获取表头
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2. 将每一个对象对象中的值存到一个数组中 ，将每个数组存储到大数组中
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async onclick() {
      // 1.发送请求获取数据
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code !== 10000) return
        // 2.需要将获取到的数据转换为excel格式
        console.log('res.data.rows', res.data.rows)
        const { headers, data } = this.dataForm(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
